﻿using System;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;


namespace hxweditor
{
	
	public class ScenePreViewEditor:BaseEditorWindow<ScenePreViewEditor>
	{

		private static string SceneEditorScenePathKey = "SceneEditor_SceneListPath";
		private static string SceneListPath = "";

		private List<ScenePreViewEditorVo> sceneVoList = new List<ScenePreViewEditorVo> ();

		ScenePreViewEditor()
		{
			this.titleContent = new GUIContent("场景预览窗口");
		}

        void Update()
        {
            if (sceneVoList.Count == 0)
            {
                InitSceneVo();
            }
        }

		void OnEnable ()
		{
			SceneListPath = PlayerPrefs.GetString (SceneEditorScenePathKey, "请输入场景根目录");
            InitSceneVo();
		}

        private void InitSceneVo()
        {
            sceneVoList.Clear();
            if (Directory.Exists(SceneListPath))
            {
                string[] dirList = Directory.GetDirectories(SceneListPath);
                foreach (string dirPath in dirList)
                {
                    ScenePreViewEditorVo vo = new ScenePreViewEditorVo();
                    vo.path = dirPath;
                    vo.sceneName = FileTool.GetDirectoryName(vo.path);
                    sceneVoList.Add(vo);
                }
            }
        }

		void OnDisable ()
		{
			PlayerPrefs.SetString (SceneEditorScenePathKey, SceneListPath);
		}

		void OnGUI ()
		{

			SceneListPath = ShowInputString ("场景目录:", SceneListPath);

			ShowSpaceLine (1);

            foreach (ScenePreViewEditorVo vo in sceneVoList)
            {
                if (ShowButton(vo.sceneName))
                {
                    OpenScene(vo);
                }
            }

		}

		private void LoadSceneVo ()
		{
			sceneVoList.Clear ();
			if (!Directory.Exists (SceneListPath)) {
				Debug.LogError ("找不到目录:" + SceneListPath);
				return;
			}

			string[] dirList = Directory.GetDirectories (SceneListPath);

			foreach (string dirPath in dirList) {
				sceneVoList.Add (ScenePreViewEditorVo.Creat (dirPath));
			}
		}

		private void OpenScene (ScenePreViewEditorVo vo)
		{

            int SceneCount = EditorSceneManager.sceneCount;

            for (int i = SceneCount-1; i > -1; i--)
            {
                EditorSceneManager.CloseScene(EditorSceneManager.GetSceneAt(i), true);
            }

            string[] sceneList = Directory.GetFiles(vo.path);

            foreach(string scenePath in sceneList){
                string ext = FileTool.GetFileExtension(scenePath);
                if(ext == ".unity")
                    EditorSceneManager.OpenScene(PathTool.RemoveTo(scenePath,PathTool.AssetsFlag),OpenSceneMode.Additive);
            }
		}

	}
}

